﻿using log4net;
using ServerControl.Model;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;

namespace ServerControl.Dal
{
    public class AccountDal : DbBase
    {
        private static ILog logger = LogManager.GetLogger("AccountDal");

        public static bool Insert(Account account)
        {
            var isSuccess = false;

            try
            {
                if (!Instance.Queryable<Account>().Where(t => t.UniqueId == account.UniqueId).Any())
                {
                    isSuccess = Instance.Insertable(account).ExecuteCommand() > 0;
                }
                else if (!string.IsNullOrEmpty(account.Cookies))
                {
                    isSuccess = Instance.Updateable<Account>().SetColumns(t => new Account { Cookies = account.Cookies, NickName = account.NickName }).ExecuteCommand() > 0;
                }
            }
            catch (Exception ex)
            {
                logger.Equals(ex);
            }

            return isSuccess;
        }

        public static bool Delete(string userName, List<string> uniqueIds)
        {
            return Instance.Deleteable<Account>().Where(t => t.UserName == userName && uniqueIds.Contains(t.UniqueId)).ExecuteCommand() > 0;
        }

        public static bool UpdateCookie(string userName, string uniqueId, string cookies)
        {
            return Instance.Updateable<Account>().SetColumns(s => s.Cookies == cookies).Where(t => t.UserName == userName && t.UniqueId == uniqueId).ExecuteCommand() > 0;
        }

        public static List<Account> ListPage(ref int records, int page, int limit, string userName, string nickName = "", string status = "")
        {
            return Instance
                .Queryable<Account>()
                .Where(t => t.UserName == userName)
                .WhereIF(!string.IsNullOrEmpty(nickName), s => s.NickName.Contains(nickName))
                .WhereIF(status == "login", s => s.Cookies.Length > 0)
                .WhereIF(status == "unlogin", s => s.Cookies.Length == 0)
                .ToPageList(page, limit, ref records);
        }
    }
}
